﻿using AccessDoorPolice.CommonResource;
using AccessDoorPolice.Converters;
using AccessDoorPolice.Model;
using AccessDoorPolice.Reader;
using LiHelperLibrary;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlTypes;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml;

namespace AccessDoorPolice
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            InitBinding();
            InitTimer();
            ReadXML(out List<RFID> _rfid);
            // CommTcp(out List<RFID> _rfid);

            COMMREDER(_rfid);

        }
        readonly CommResource _commonResource = CommResource.StaticCommonResource;
        RFIDBUING rfidbuing = new RFIDBUING();
        System.Timers.Timer _timer;
        /// <summary>
        /// 删除列表
        /// </summary>
        DispatcherTimer _timer2;

        private static int stainfor = -1;
        List<RFID> ReadXML(out List<RFID> _rfid)
        {
            _rfid = new List<RFID>();
            try
            {

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load("RFID.xml");

                // 获取根节点
                XmlNodeList rfidNodes = xmlDoc.GetElementsByTagName("rfid");

                // 遍历每个rfid节点
                foreach (XmlNode rfidNode in rfidNodes)
                {
                    // 获取子节点的值
                    string ip = rfidNode.SelectSingleNode("ip").InnerText;
                    string port = rfidNode.SelectSingleNode("port").InnerText;
                    string antList = rfidNode.SelectSingleNode("antList").InnerText;
                    string antA = rfidNode.SelectSingleNode("antA").InnerText;
                    string antB = rfidNode.SelectSingleNode("antB").InnerText;
                    string antC = rfidNode.SelectSingleNode("antC").InnerText;
                    string antD = rfidNode.SelectSingleNode("antD").InnerText;
                    string triggerinfrared = rfidNode.SelectSingleNode("triggerinfrared").InnerText;
                    string infor = rfidNode.SelectSingleNode("infor").InnerText;
                    RFID rfid = new RFID();
                    rfid.IP = ip.ToString();
                    rfid.Port = Convert.ToInt32(port);
                    string[] AntList = antList.Split(',');
                    List<int> Ant = new List<int>();
                    for (int i = 0; i < AntList.Length; i++)
                    {
                        Ant.Add(Convert.ToInt32(AntList[i]));
                    }
                    rfid.Antennas = Ant;
                    rfid.infor = Convert.ToInt32(infor);
                    List<Powerlist> _list = new List<Powerlist>();
                    Powerlist powerlist = new Powerlist();
                    powerlist.Ant = "1";
                    powerlist.Power = antA;
                    _list.Add(powerlist);
                    Powerlist powerlista = new Powerlist();
                    powerlista.Ant = "2";
                    powerlista.Power = antB;
                    _list.Add(powerlista);
                    Powerlist powerlistb = new Powerlist();
                    powerlistb.Ant = "3";
                    powerlistb.Power = antC;
                    _list.Add(powerlistb);
                    Powerlist powerlistc = new Powerlist();
                    powerlistc.Ant = "4";
                    powerlistc.Power = antD;
                    _list.Add(powerlistc);
                    rfid.Powerlist = _list;
                    rfid.Triggerinfrared = Convert.ToInt32(triggerinfrared);
                    rfid.Triggerinfraredout = Convert.ToInt32(triggerinfrared) - 1;
                    rfid.Triggerinfraredinfo = Convert.ToInt32(triggerinfrared) - 2;
                    _rfid.Add(rfid);
                }
            }
            catch (Exception e)
            {
                AppLog.Error("初始化异常" + e);
            }
            return _rfid;
        }
        void InitBinding()
        {
            Displaydate.SetBinding(TextBlock.TextProperty, new Binding(nameof(_commonResource.ClientProperty.Now))
            { Source = _commonResource.ClientProperty, Converter = new DateToClientDateConverter() });
        }
        private void InitTimer()
        {
            //设置定时间隔(毫秒为单位)
            int interval = 1000;
            _timer = new System.Timers.Timer(interval)
            {
                AutoReset = true,
                Enabled = true
            };
            //绑定Elapsed事件
            _timer.Elapsed += new ElapsedEventHandler(TimerUp);
            _timer2 = new DispatcherTimer();
            int clearTime = Convert.ToInt32(ConfigurationManager.AppSettings["clearTime"]) * 1;
            _timer2.Interval = TimeSpan.FromSeconds(clearTime);
            _timer2.Tick += Timer_Tick;
        }
        private void TimerUp(object sender, ElapsedEventArgs e)
        {
            _commonResource.ClientProperty.Now = DateTime.Now;
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (epcsinfo.Count == 0)
            {
                _timer2.Stop();
            }
            else
            {
                int countValue = epcsinfo.Count();
                epcsinfo.RemoveAt(0);
            }
        }
        //private void Button_Click_1(object sender, RoutedEventArgs e)
        //{
        //    Environment.Exit(0);
        //    this.WindowStyle = WindowStyle.SingleBorderWindow;
        //    Application.Current.Shutdown();
        //}

        void COMMREDER(List<RFID> rifd)
        {
            try
            {
                foreach (RFID item in rifd)
                {
                    ReaderType readerType;
                    readerType = rfidbuing.Conformitiesmethod(RfidType.Open, item);
                    Thread.Sleep(1000);
                    if (readerType.StatusCode != 0)
                    {
                        string strcause = rfidbuing.GetReturnCodeDesc(readerType.StatusCode);
                        AppLog.Info($"设备Ip为{item.IP}，登录失败,原因:{strcause}");
                        suass.Text = $"设备Ip为{item.IP}，登录失败,原因:{strcause}";
                        continue;
                    }
                    readerType = rfidbuing.Conformitiesmethod(RfidType.SetAnt, item);
                    if (readerType.StatusCode != 0)
                    {
                        string strcause = rfidbuing.GetReturnCodeDesc(readerType.StatusCode);
                        AppLog.Info($"设备Ip为{item.IP}，设置天线失败,原因:{strcause}");
                        suass.Text = $"设备Ip为{item.IP}，设置天线失败,原因:{strcause}";
                        continue;
                    }
                    readerType = rfidbuing.Conformitiesmethod(RfidType.SetPower, item);
                    if (readerType.StatusCode != 0)
                    {
                        string strcause = rfidbuing.GetReturnCodeDesc(readerType.StatusCode);
                        AppLog.Info($"设备Ip为{item.IP}，设置功率失败,原因:{strcause}");
                        suass.Text = $"设备Ip为{item.IP}，设置功率失败,原因:{strcause}";
                        continue;
                    }
                    RFIDBUSINES._rfid.Add(item);
                    AppLog.Info($"设备Ip为{item.IP}，登录成功");
                    suass.Text = $"设备Ip为{item.IP}，登录成功";
                }
            }
            catch (Exception ex)
            {
                AppLog.Error(ex.Message);
            }
        }
        void RFIDBUG()
        {
            foreach (RFID item in RFIDBUSINES._rfid)
            {
                Thread thread = new Thread(GenerateData);
                thread.Start(item);
            }
        }
        static List<string> epcs = new List<string>();
        static List<ResultepcModel> epcsinfo = new List<ResultepcModel>();
        int time = Convert.ToInt32(ConfigurationManager.AppSettings["time"]);

        public void GenerateData(object e)
        {
            int state = -1;
            int direction = 0;
            RFID rfid = new RFID();
            if (e is RFID)
            {
                rfid = (RFID)e;
            }
            ReaderType readerType;
            List<string> strList = new List<string>();

            while (true)
            {
                try
                {
                    direction = 0;
                    readerType = rfidbuing.Conformitiesmethod(RfidType.GetGPIOStatus, rfid);
                    if (readerType.StatusCode == 48)
                    {
                        readerType = rfidbuing.Conformitiesmethod(RfidType.ReConnDisconnected, rfid);
                    }
                    if (readerType.StatusCode != 0)
                    {
                        continue;
                    }
                    if (readerType.GPIOCode == rfid.Triggerinfrared)
                    {
                        continue;
                    }
                    if (state == -1)
                    {
                        state = readerType.GPIOCode;
                        readerType = rfidbuing.Conformitiesmethod(RfidType.Inventory_G2, rfid);
                        if (readerType.ListEPCTag.Count > 0)
                        {
                            strList.AddRange(readerType.ListEPCTag);
                        }
                        continue;
                    }
                    if (readerType.GPIOCode == state)
                    {
                        state = -1;
                        strList.Clear();
                        continue;
                    }
                    if (readerType.GPIOCode != state)
                    {
                        if (rfid.infor == 0)
                        {
                            if (readerType.GPIOCode == rfid.Triggerinfraredout)
                            {
                                direction = 1;
                            }
                            else if (readerType.GPIOCode == rfid.Triggerinfraredinfo)
                            {
                                direction = 2;
                            }
                            else
                            {
                                if (state == rfid.Triggerinfraredout)
                                {
                                    direction = 1;
                                }
                                else if (state == rfid.Triggerinfraredinfo)
                                {
                                    direction = 2;
                                }
                                else
                                {
                                    state = -1;
                                    strList.Clear();
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            if (readerType.GPIOCode == rfid.Triggerinfraredout)
                            {
                                direction = 2;
                            }
                            else if (readerType.GPIOCode == rfid.Triggerinfraredinfo)
                            {
                                direction = 1;
                            }
                            else
                            {
                                if (state == rfid.Triggerinfraredout)
                                {
                                    direction = 2;
                                }
                                else if (state == rfid.Triggerinfraredinfo)
                                {
                                    direction = 1;
                                }
                                else
                                {
                                    state = -1;
                                    strList.Clear();
                                    continue;
                                }
                            }
                        }
                    }
                    strList = strList.Where(str => str != null).Distinct().ToList();

                    CKBill(strList.ToArray(), direction, out List<ResultepcModel> resultepcModels, out bool isckbill);
                    if (resultepcModels != null)
                    {

                        epcsinfo.AddRange(resultepcModels);
                    }
                    Task.Run(() =>
                    {
                        ABCDEFG(rfid, direction, epcsinfo, isckbill);

                        if (epcsinfo.Count > 0)
                        {
                            if (!_timer2.IsEnabled)
                            {
                                _timer2.Start();
                            }
                        }
                    });
                    strList.Clear();
                    state = -1;
                }
                catch (Exception ex)
                {
                    AppLog.Error(ex);
                }

            }

        }


        public void CKBill(string[] EPC, int direct, out List<ResultepcModel> resultepcModels, out bool isckbill)
        {
            string url = null;
            List<string> strings = new List<string>();

            strings = EPC.ToList();

            var body = new { epc = strings, direction = direct };
            string resJson = null;
            ResultCKBill result = new ResultCKBill();
            isckbill = false;
            List<ResultepcModel> wqe = new List<ResultepcModel>();
            ResultCKBill res = new ResultCKBill();
            try
            {
                string urlBase = ConfigurationManager.AppSettings["baseUrl"];
                url = $"{urlBase}/app/business/door/CKBill";
                resJson = InterfaceHelper.RequestInterface(body, url);
                res = TypeConversion.JsonToObject<ResultCKBill>(resJson);
                if (res.code == 200)
                {
                    foreach (var item in res.data)
                    {
                        if (item.status != 0)
                        {
                            //关闭三色灯 true false
                            isckbill = true;
                        }
                        ResultepcModel resultepcModel = new ResultepcModel();
                        resultepcModel.epc = item.epc;
                        resultepcModel.name = item.name;
                        resultepcModel.message = item.massage;
                        resultepcModel.time = DateTime.Now.ToString("HH:mm:ss");
                        wqe.Add(resultepcModel);
                    }
                    resultepcModels = wqe;
                }
            }
            catch (Exception ex)
            {
                Log.PrintError(ex);
            }
            finally
            {
                AppLog.Info($"后台全地址{TypeConversion.ObjectToJson(url)} ");
                AppLog.Info($"读取到epc标签{TypeConversion.ObjectToJson(strings)} ");

                AppLog.Info($"传入的参数{TypeConversion.ObjectToJson(body)} ，返回的参数{resJson}");
                resultepcModels = wqe;

            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            RFIDBUG();
        }

        void ABCDEFG(RFID rfid, int direction, List<ResultepcModel> list, bool isckbill)
        {
            if (list == null)
            {
                return;
            }
            string infors = "";
            List<Person> _person = new List<Person>();
            int idi = 1;
            string INFOR = string.Empty;
            if (direction == 2)
            {
                infors = "出库";
            }
            else
            {
                infors = "入库";
            }
            //去重处理
            list.GroupBy(x => x.epc)
                           .Select(x => x.First());
            foreach (var item in list)
            {
                Person person = new Person();
                person.ID = idi;
                person.EpcCode = item.epc;
                person.wuzhiname = item.name;
                person.infor = infors;
                person.massage = item.message;
                person.ProductTime = item.time;
                _person.Add(person);
                idi++;
            }
            this.Dispatcher.Invoke(DispatcherPriority.Normal, (System.Threading.ThreadStart)async delegate ()
            {
                try
                {
                    var person = _person.GroupBy(x => x.EpcCode)
                               .Select(x => x.First()).ToList();
                    dataGrid1.ItemsSource = person;
                    SumNum.Text = person.Count().ToString();
                    dataGrid1.Items.Refresh();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });
            //控制报警 1红灯
            if (isckbill)
            {
                ReaderType readerType = rfidbuing.Conformitiesmethod(RfidType.SetGPIO, rfid, 1);
                int AlarmTime = Convert.ToInt32(ConfigurationManager.AppSettings["AlarmTime"]);
                Task.Delay(AlarmTime * 1000).Wait();
                readerType = rfidbuing.Conformitiesmethod(RfidType.SetGPIO, rfid, 0);
            }
        }
        //自定义去重类
        public class EpcEqualityComparer : IEqualityComparer<Person>
        {

            public bool Equals(Person x, Person y) { return x.ID == y.ID; }

            public int GetHashCode(Person obj)
            {
                throw new NotImplementedException();
            }
        }


        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}
